﻿using System;
using System.ComponentModel;
using System.Text.RegularExpressions;
using Kiva7.Settings;
using Kiva7.ViewModels;

namespace Kiva7.Translations
{
    public class Translation : BaseViewModel
    {
        public Translation()
        {
        }

        public Translation(string originalText)
        {
            _original = StripTags(originalText);
        }

        static Regex regex = new Regex(@"</?\w*>", RegexOptions.Compiled);

        private static string StripTags(string value)
        {
            if (string.IsNullOrEmpty(value))
                return null;

            return regex.Replace(value, "");
        }

        private string _original;
        private string _translated;

        public string Original
        {
            get
            {
                return _original;
            }
            set
            {
                _original = value;
            }
        }

        public string Text
        {
            get
            {
                if (string.IsNullOrEmpty(_translated))
                {
                    TranslateTextAutomatic();
                    return _original;
                }
                return _translated;
            }
        }

        private bool _translationStarted = false;

        private void TranslateTextAutomatic()
        {
            if (!_translationStarted
                && AppSettings.Current.TranslationSetting == TranslatorOption.Automatic
                &&  !string.IsNullOrEmpty(Original))
            {
                _translationStarted = true;
                TranslatorContext.TranslateTextAutomatic(this);
            }
        }

        public void TranslateTextWithDetect()
        {
            TranslatorContext.TranslateTextWithDetect(this);
        }

        public void TranslateText()
        {
            if (!_translationStarted
                && !string.IsNullOrEmpty(Original))
            {
                _translationStarted = true;
                TranslatorContext.TranslateText(this);
            }
        }

        public string Translated
        {
            get
            {
                return _translated;
            }
            set
            {
                _translated = value;
                NotifyPropertyChanged("Text");
                NotifyPropertyChanged("Translated");
            }
        }

        public bool IsTranslated
        {
            get
            {
                return !string.IsNullOrEmpty(_translated);
            }
        }

        public override string ToString()
        {
            return Text;
        }

    }
}